﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace GloboTicketAdmin.API.Converters
{
    /// <summary>
    /// 自定义 DateTime 序列化转换器（指定格式）
    /// </summary>
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        private readonly string _format;

        /// <summary>
        /// 构造函数（指定日期格式）
        /// </summary>
        /// <param name="format">日期格式（如：yyyy-MM-dd HH:mm:ss）</param>
        public DateTimeConverter(string format)
        {
            _format = format;
        }

        /// <summary>
        /// 反序列化（字符串转 DateTime）
        /// </summary>
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(reader.GetString());
            DateTime dateTime = dateTimeOffset.UtcDateTime; // 转换为UTC时间
            //return DateTime.ParseExact(reader.GetString(), _format, CultureInfo.InvariantCulture);
            return dateTime;
        }

        /// <summary>
        /// 序列化（DateTime 转字符串）
        /// </summary>
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_format, CultureInfo.InvariantCulture));
        }
    }

    /// <summary>
    /// 支持可空 DateTime 的转换器
    /// </summary>
    public class NullableDateTimeConverter : JsonConverter<DateTime?>
    {
        private readonly string _format;

        public NullableDateTimeConverter(string format)
        {
            _format = format;
        }

        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var value = reader.GetString();
            return string.IsNullOrEmpty(value)
                ? null
                : DateTime.ParseExact(value, _format, CultureInfo.InvariantCulture);
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            if (value.HasValue)
            {
                writer.WriteStringValue(value.Value.ToString(_format, CultureInfo.InvariantCulture));
            }
            else
            {
                writer.WriteNullValue();
            }
        }
    }
}
